<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/17
 * Time: 0:08
 */

namespace app\api\model;


use think\Model;

class WeTopic extends Model
{

    protected $autoWriteTimestamp = true;

    /**
     * 热门话题
     * @param int $uid
     * @param bool $backend
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hotTopic($uid = 0, $backend = false)
    {
        $map = [];
        if ($uid) {
            $field = 't.id,u.nick_name,u.we_nick_name,u.reset_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat,case l.user_id when l.user_id then 1 else 0 end as is_liked,case td.user_id when td.user_id then 1 else 0 end as is_detailed';
        } else {
            $field = 't.id,t.category_id,u.nick_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat';
        }
        $config = module_config('sd');
        $hot_time_config = $config['hot_time'];
        $hot_time = $hot_time_config * 60 * 60;
        $time = time() - $hot_time;
//        $first = $config['hot_first'];
        $first = 5;
        $result_data = [];
        switch ($first) {
            case 0:
                //点赞优先
                $likes = new WeLikes();
                $data = $likes->hotId($time);
                if (isset($data['num']) && $data['num']) {
                    $topic_id = $data['topic_id'];
                    $result_data = self::hotTopicDetail($topic_id, $uid, $field, $map, $backend);
                }
                break;
            case 1:
                //评论量优先
                $detail = new WeTopicDetail();
                $data = $detail->hotId($time);
                if (isset($data['num']) && $data['num']) {
                    $topic_id = $data['topic_id'];
                    $result_data = self::hotTopicDetail($topic_id, $uid, $field, $map, $backend);
                }
                break;
            default:
                //点赞+评论 总和
                $likes = new WeLikes();
                $likes_data = $likes->where(['is_delete' => 0, 'create_time' => ['>=', $time]])->field('topic_id,count(*) as num')->group('topic_id')->orderRaw('count(*) desc')->select();
                if (!empty($likes_data)) {
                    $likes_data = collection($likes_data)->toArray();
                }

                $detail = new WeTopicDetail();
                $detail_data = $detail->where(['is_delete' => 0, 'create_time' => ['>=', $time]])->field('topic_id,count(*) as number')->group('topic_id')->orderRaw('count(*) desc')->select();
                if (!empty($detail_data)) {
                    $detail_data = collection($detail_data)->toArray();
                }
                $topic_ids = [];
                if (empty($likes_data) && empty($detail_data)) {
                    return [];
                } elseif (empty($likes_data) && count($detail_data)) {
                    $topic_ids = array_column($detail_data, 'topic_id');
                    $data = array_map(function ($item) {
                        $item['total'] = $item['number'];
                        return $item;
                    }, $detail_data);
                } elseif (empty($detail_data) && count($likes_data)) {
                    $topic_ids = array_column($likes_data, 'topic_id');
                    $data = $data = array_map(function ($item) {
                        $item['total'] = $item['num'];
                        return $item;
                    }, $likes_data);
                } else if (count($likes_data) && count($detail_data)) {
                    $temp_arr = [];
                    foreach ($likes_data as $key => &$likes_datum) {
                        foreach ($detail_data as $k => &$detail_datum) {
                            if ($likes_datum['topic_id'] == $detail_datum['topic_id']) {
                                $temp = array_merge($likes_datum, $detail_datum);
                                $temp['total'] = $likes_datum['num'] + $detail_datum['number'];
                                $temp_arr[] = $temp;
                            } else {
                                $likes_datum['total'] = $likes_datum['num'];
                                $likes_datum['number'] = 0;
                                $detail_datum['total'] = $detail_datum['number'];
                                $detail_datum['num'] = 0;
                                $temp_arr[] = $detail_datum;
                                unset($detail_datum);
                            }
                        }
                    }
                    $data = array_merge($likes_data, $temp_arr);
                    $topic_ids = array_column($data, 'topic_id');
                }
                //判断ID是否有效
                $maps = [
                    'id' => ['in', implode(',', $topic_ids)],
                    'status' => 1,
                    'is_delete' => 0
                ];
                $ex = self::where($maps)->column('id');
                $data = array_filter($data, function ($item) use ($ex) {
                    if (in_array($item['topic_id'], $ex)) {
                        return true;
                    }
                });
                array_multisort(array_column($data, 'total'), SORT_DESC, $data);
                if (empty($data)) {
                    return [];
                }
                $topic_id = array_values($data)[0]['topic_id'];
                $result_data = self::hotTopicDetail($topic_id, $uid, $field, $map, $backend);
        }
        return $result_data;
    }

    /**
     * 热门话题详情
     * @param $topic_id
     * @param $uid
     * @param $field
     * @param $map
     * @param $backend
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function hotTopicDetail($topic_id, $uid, $field, $map, $backend)
    {
        $model = new self();
        $result_data = $model->alias('t')
            ->join('__WE_LIKES__ l', 't.id = l.topic_id and t.status = 1 and t.is_delete = 0 and l.is_delete = \'0\' and l.user_id = \'' . $uid . '\'', 'left')
            ->join('__WE_USERS__ u', 'u.id = t.user_id', 'left')
            ->join('__WE_TOPIC_DETAIL__ td', 'td.topic_id = t.id and td.user_id = ' . $uid, 'left')
            ->where(array_merge(['t.id' => $topic_id], $map))
            ->field($field)
            ->fetchSql(false)
            ->find();
        return $backend ? $result_data->toArray() : $result_data;
    }

    /**
     * 首页话题列表
     * @param $data
     * @param string $uid
     * @return array
     * @throws \think\exception\DbException
     */
    public function topicList($data, $uid = '0')
    {
        $map = [];
        if ($uid) {
            $field = 'distinct(t.id),u.nick_name,u.we_nick_name,u.reset_name,t.likes,t.content,t.photos,t.details,t.create_time, t.location,t.longt,t.lat,case l.user_id when l.user_id then 1 else 0 end as is_liked,case td.user_id when td.user_id then 1 else 0 end as is_detailed';
        } else {
            $field = 'distinct(t.id),u.nick_name,u.we_nick_name,u.reset_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat';
        }
        if (isset($data['start_time']) && $data['start_time'] && isset($data['end_time']) && $data['end_time']) {
            $map['t.create_time'] = [['>=', $data['start_time']], ['<', $data['end_time']], 'and'];
        }
        if (isset($data['category_id']) && $data['category_id']) {
            $map['t.category_id'] = $data['category_id'];
        }
        $order = '';
        if (isset($data['order'])) {
            switch ($data['order']) {
                case 1:
                    $order = 't.create_time desc';
                    break;
                case 2:
                    $order = 't.create_time asc';
                    break;
                default:
                    $order = 't.create_time desc';
            }
        }
        if (isset($data['ids'])) {
            $map = array_merge($map, $data['ids']);
        }
        $model = new self();
        $data = $model->alias('t')
            ->join('__WE_LIKES__ l', 't.id = l.topic_id and l.is_delete = \'0\' and l.user_id = \'' . $uid . '\'', 'left')
            ->join('__WE_TOPIC_DETAIL__ td', 'td.topic_id = t.id and td.is_delete = \'0\' and td.user_id = \'' . $uid . '\'', 'left')
            ->join('__WE_USERS__ u', 'u.id = t.user_id')
            ->where(array_merge(['t.is_delete' => 0, 't.status' => 1], $map))
            ->field($field)
            ->order($order)
//            ->buildSql(true);
//        echo $data;exit;
            ->paginate(config('sd_config.list_len'))->each(function ($item) {
                $item->append(['photos']);
            })->toArray();
        return empty($data) ? [] : $data;
    }

    /**
     * 格式化创建时间
     * @param $value
     * @return false|string
     */
    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    /**
     * 用户话题列表
     * @param $uid
     * @param $data
     * @param bool $hot
     * @return array
     * @throws \think\exception\DbException
     */
    public function userTopicList($uid, $data, $hot = false)
    {
        $order = '';
        $map = [];
        if (isset($data['order'])) {
            switch ($data['order']) {
                case 1:
                    $order = 'create_time desc';
                    break;
                case 2:
                    $order = 'create_time asc';
                    break;
                default:
                    $order = 'create_time desc';
            }
        }
        if (isset($data['start_time']) && isset($data['end_time'])) {
            $map['create_time'] = [['>=', $data['start_time']], ['<', $data['end_time']], 'and'];
        }
        if (!$hot) {
            $data = self::where(array_merge(['status' => 1, 'is_delete' => 0, 'user_id' => $uid], $map))
                ->field('id,content,photos,create_time,location,longt,lat,likes,details')
                ->order($order)
                ->paginate(config('list_row'))
                ->toArray();
        } else {
            $data = self::where(array_merge(['status' => 1, 'is_delete' => 0, 'user_id' => $uid], $map))
                ->field('id,content,photos,create_time,location,longt,lat,likes,details')
                ->orderRaw('likes + details desc,create_time desc')
                ->paginate(config('list_row'))
                ->toArray();
        }
        return empty($data) ? [] : $data;
    }


    /**
     * 图片获取器
     * @param $value
     * @return array
     */
    public function getPhotosAttr($value)
    {
        return array_map(function ($item) {
            return config('web_site_domain') . $item;
        }, get_files_path(explode(',', $value)));
    }

    /**
     * 最热门
     * @param $uid
     * @param $category_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function theHot($uid, $category_id)
    {
        if ($uid) {
            $field = 'distinct(t.id),t.content,t.photos,t.likes,t.details,t.category_id,t.create_time,t.location,t.longt,t.lat,case l.user_id when l.user_id then 1 else 0 end as is_liked,case td.user_id when td.user_id then 1 else 0 end as is_detailed,u.nick_name,u.reset_name,u.we_nick_name';
        } else {
            $field = 't.id,t.likes,t.content,t.photos,t.details,t.category_id,t.create_time,t.location,t.longt,t.lat,u.nick_name,u.reset_name,u.we_nick_name';
            $map = [];
        }
        $model = new self();
        $data_list = $model->alias('t')
            ->join('__WE_LIKES__ l', 't.id = l.topic_id and t.status = 1 and t.is_delete = 0 and l.is_delete = 0 and l.user_id = ' . $uid, 'left')
            ->join('__WE_TOPIC_DETAIL__ td', 't.id = td.topic_id and td.user_id = ' . $uid, 'left')
            ->join('__WE_USERS__ u', 't.user_id = u.id')
            ->field($field)
            ->orderRaw('t.likes + t.details desc,t.create_time desc')
            ->where(['t.category_id' => $category_id])
//            ->fetchSql(true)
//            ->select();
//        echo $data_list;exit;
            ->paginate(config('sd_config.list_len'))
            ->toArray();
        return empty($data_list['data']) ? [] : $data_list;
    }


    /**
     * getTopicInfoByID
     * @param $id
     * @param $uid
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getTopicInfoByID($id, $uid)
    {
        if ($uid) {
            $field = 't.id,u.nick_name,u.reset_name,u.we_nick_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat, case l.user_id when l.user_id then 1 else 0 end as is_liked,case td.user_id when td.user_id then 1 else 0 end as is_detailed';
        } else {
            $field = 't.id,u.nick_name,u.reset_name,u.we_nick_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat';
        }
        $model = new self();
        $data = $model->alias('t')
            ->join('__WE_LIKES__ l', 't.id = l.topic_id and l.is_delete = \'0\' and l.user_id = \'' . $uid . '\'', 'left')
            ->join('__WE_TOPIC_DETAIL__ td', 'td.topic_id = t.id and td.is_delete = \'0\' and td.user_id = \'' . $uid . '\'', 'left')
            ->join('__WE_USERS__ u', 'u.id = t.user_id')
            ->where(array_merge(['t.is_delete' => 0, 't.status' => 1, 't.id' => $id]))
            ->field($field)
            ->fetchSql(false)
            ->find();
        return empty($data) ? [] : $data;
    }

    public function deleteTopic($uid, $id)
    {
        return self::save(['is_delete' => 1], ['user_id' => $uid, 'id' => $id]);
    }

    public function reportTopic($id)
    {
        return self::where(['id' => $id])->update(['report' => 1]);
    }

    public function getTopicInfo($id)
    {
        $info = self::where(['id' => $id])->find();
        return empty($info) ? [] : $info->toArray();
    }


    public function searchByTitle($title)
    {
        if (!is_array($title)) {
            $data_list = self::where(['title' => ['like', '%' . $title . '%']])->paginate(config('list_len'));
        } else {
            $map = [];
            foreach ($title as $item) {
                $map[] = ['title' => ['like', '%' . $item . '%']];
            }
            $data_list = self::where($map)->paginate(config('list_len'));
        }
        return $data_list;
    }

    public function searchByContent($content, $uid = 0)
    {
        $model = new  self();

        if ($uid) {
            $field = 'distinct(t.id),u.nick_name,u.we_nick_name,u.reset_name,t.likes,t.content,t.photos,t.details,t.create_time, t.location,t.longt,t.lat,case l.user_id when l.user_id then 1 else 0 end as is_liked,case td.user_id when td.user_id then 1 else 0 end as is_detailed';
        } else {
            $field = 'distinct(t.id),u.nick_name,u.we_nick_name,u.reset_name,t.likes,t.content,t.photos,t.details,t.create_time,t.location,t.longt,t.lat';
        }
        if (!is_array($content)) {
            $data_list = $model->alias('t')
                ->join('__WE_LIKES__ l', 't.id = l.topic_id and l.is_delete = \'0\' and l.user_id = \'' . $uid . '\'', 'left')
                ->join('__WE_TOPIC_DETAIL__ td', 'td.topic_id = t.id and td.is_delete = \'0\' and td.user_id = \'' . $uid . '\'', 'left')
                ->join('__WE_USERS__ u', 'u.id = t.user_id','left')
                ->field($field)
                ->where(['t.content' => ['like', '%' . $content . '%']])
                ->paginate(config('list_len'))
                ->toArray();
        } else {
            $map = [];
            foreach ($content as $item) {
                $map[] = ['content' => ['like', '%' . $item . '%']];
            }
            $data_list = $data_list = $model->alias('t')
                ->join('__WE_LIKES__ l', 't.id = l.topic_id and l.is_delete = \'0\' and l.user_id = \'' . $uid . '\'', 'left')
                ->join('__WE_TOPIC_DETAIL__ td', 'td.topic_id = t.id and td.is_delete = \'0\' and td.user_id = \'' . $uid . '\'', 'left')
                ->join('__WE_USERS__ u', 'u.id = t.user_id','left')
                ->field($field)
                ->where($map)
                ->paginate(config('list_len'))
                ->toArray();
        }
        return $data_list;
    }
}